<?php

//define ("PB_CRYPT_LINKS" , "1");

function DoEvents($this) {
	global $_CONF , $_TSM;

	$_TSM["MENU"] = "";

	//checking if user is logged in
	if (!$_SESSION["minibase"]["user"]) {

		if ($_SERVER["REQUEST_METHOD"] == "POST") {

			//autentificate
			$user = $this->db->QFetchArray("select * from {$this->tables[users]} where `user_login` = '{$_POST[user]}' AND `user_password` = '{$_POST[pass]}'");

			if (is_array($user)) {
				$_SESSION["minibase"]["user"] = 1;
				$_SESSION["minibase"]["raw"] = $user;

				//redirecing to viuw sites
				header("Location: $_CONF[default_location]");
				exit;
			} else
				return $this->templates["login"]->blocks["Login"]->output;

		} else
			return $this->templates["login"]->blocks["Login"]->output;
	}
	if ($_SESSION["minibase"]["raw"]["user_level"] == 0) {
		$_TSM["MENU"] = $this->templates["login"]->blocks["MenuAdmin"]->output;
	} else {
		$_TSM["MENU"] = $this->templates["login"]->blocks["MenuUser"]->output;
	}

	if (!$_POST["task_user"])
		$_POST["task_user"] = $_SESSION["minibase"]["user"];

	if($_SESSION["minibase"]["raw"]["user_level"] == 1) {
		$_CONF["forms"]["adminpath"] = $_CONF["forms"]["userpath"];
	}

	switch ($_GET["sub"]) {
		case "logout":
			unset($_SESSION["minibase"]["user"]);
			header("Location: index.php");

			return $this->templates["login"]->EmptyVars();
		break;

		case "export.transactions":
			header("Content-Type: text/x-csv");
			header("Content-Disposition: inline; filename=transactions.csv");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: public");

			echo putcsv(array( "Customer Name","Service Date","Service Time","Description","Work Done","Service Actual Date","Service Actual Time"));

			$products = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[customers]} , {$this->tables[calls]} , {$this->tables[types]} WHERE service_type=type_id AND service_contact_data=client_id order by client_name asc");

			if (is_array($products)) {
				foreach ($products as $key => $val) {
					echo putcsv(array(
							$val["client_name"] , 
							date ("m/d/Y",$val["service_date"]),
							date ("g:i a",$val["service_date"]),
							str_replace("\r\n",'\n',$val["service_description"]),
							str_replace("\r\n",'\n',$val["service_work"]),
							date ("m/d/Y",$val["service_visit"]),
							date ("g:i a",$val["service_visit"])
						));
				}						
			}

			die();

		break;

		case "export.customers":

			header("Content-Type: text/x-csv");
			header("Content-Disposition: inline; filename=customers.csv");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: public");

			echo putcsv(array( "Name","Address","Contact Name","Phone","Alt Phone","Mobile Phone","Email","Web","Other"));

			$products = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[customers]}");

			if (is_array($products)) {
				foreach ($products as $key => $val) {
					echo putcsv(array(
							$val["client_name"] , 
							str_replace("\r\n",'\n',$val["client_address"]),
							$val["client_contact_name"],
							$val["client_phone"],
							$val["client_phone2"],
							$val["client_phone3"],
							$val["client_email"],
							$val["client_web"],
							str_replace("\r\n",'\n',$val["client_other"])
						));
				}						
			}

			die();

		break;

		case "export.products":

			header("Content-Type: text/x-csv");
			header("Content-Disposition: inline; filename=products.csv");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: public");

			echo putcsv(array("product_name","product_number","product_other"));

			$products = $this->db->QFetchRowArray("SELECT * FROM {$this->tables[products]}");

			if (is_array($products)) {
				foreach ($products as $key => $val) {
					echo putcsv(array($val["product_name"] , $val["product_number"] , str_replace("\r\n",'\n',$val["product_other"])));
				}						
			}

			die();

		break;
		
		case "workers":
		case "types":
		case "customers":
		case "notes":
		case "calls":
		case "products":
		case "products3":
		case "products2":
		case "users":

			if ($_GET["sub"] == "workers") {
				
				if ((!$_GET["action"])&&($_SESSION["minibase"]["raw"]["user_level"] != 0 )) {
					$_GET["action"] = "details";				
				}

				if ($_SESSION["minibase"]["raw"]["user_level"] == 1) {
					$_GET["user_id"] = $_SESSION["minibase"]["raw"]["user_id"]; 
					$_POST["user_id"] = $_SESSION["minibase"]["raw"]["user_id"];
				}
			}

			//there are 2 sections of groups, special groups which cant be deleted and normal groups
			if (is_subaction("products2" , "delete")) {
				$this->db->Query("DELETE from {$this->tables[calls_prods]} WHERE scall_id='{$_GET[scall_id]}'");
				header("Location:" . $_SERVER["HTTP_REFERER"]);
				exit;
			}

			if (is_subaction("products3" , "assign")) {
				$this->db->QueryInsert($this->tables["calls_prods"] , 
										array(
											"scall_product" => $_GET["product_id"],
											"scall_service" => $_GET["scall_service"]
										)
									);
				header("Location:" . $_SERVER["HTTP_REFERER"]);
				exit;
			}

			if (is_subaction("customers" , "details")) {
				switch ($_GET["section"]) {
					case "1":
						$data = new CSQLAdmin("calls2", $_CONF["forms"]["admintemplate"],$this->db,$this->tables);					
						$extra["details"]["after"] = $data->DoEvents();
					break;
					case "2":
						$data = new CSQLAdmin("notes", $_CONF["forms"]["admintemplate"],$this->db,$this->tables);					
						$extra["details"]["after"] = $data->DoEvents();
					break;
				}				
			}

			if (is_subaction("calls" , "det2")) {
				switch ($_GET["section"]) {
					case "1":
						$data = new CSQLAdmin("products2", $_CONF["forms"]["admintemplate"],$this->db,$this->tables);					
						$extra["details"]["fields"]["section"] = $data->DoEvents();
					break;

					case "2":
						$data = new CSQLAdmin("notes", $_CONF["forms"]["admintemplate"],$this->db,$this->tables);					
						$extra["details"]["fields"]["section"] = $data->DoEvents();
					break;
				}				
			}

			$data = new CSQLAdmin($_GET["sub"], $_CONF["forms"]["admintemplate"],$this->db,$this->tables,$extra);


			if (is_subaction("customers" , "")) {
				$file = $_CONF["forms"]["adminpath"] . "customers/search.xml" ;
				$search = new CForm($_CONF["forms"]["admintemplate"],$this->db,$this->tables);
				$extra2["after"] = $data->DoEvents();
				return $search->Show($file , array("values"=>$_GET) , $extra2);
			}

			if (is_subaction("calls" , "")) {
				$file = $_CONF["forms"]["adminpath"] . "calls/search.xml" ;
				$search = new CForm($_CONF["forms"]["admintemplate"],$this->db,$this->tables);
				$extra2["after"] = $data->DoEvents();
				return $search->Show($file , array("values"=>$_GET) , $extra2);
			}

			return $data->DoEvents();
		break;

		case "import.products":
		case "import.customers":
		case "import.thanks":
			$file = $_GET["sub"] . ".xml";

			$data = new CForm($_CONF["forms"]["admintemplate"],$this->db,$this->tables);

			if ($_GET["action"] == "store") {
				if (is_array($values = $data->Validate($_CONF["forms"]["adminpath"] . $file,$_POST))) {

					return $data->Show($_CONF["forms"]["adminpath"] . $file, $values);
				} else {

					$form = New CConfig( $_CONF["forms"]["adminpath"] . $file );

					switch ($_GET["sub"]) {
						case "import.products":
							$fp = @fopen ($_FILES["file"]["tmp_name"],"r"); 
							while ($import[] = @fgetcsv ($fp, 1000, ","));
							@fclose ($fp); 

							if (is_array($import)) {
								foreach ($import as $key => $record) {
									if ($key != 0) {
										foreach ($import[0] as $k => $val) {
											$_import[$key][$val] = $record[$k];
										}									
									}								
								}							
							}
							
							if (is_array($_import)) {
								foreach ($_import as $key => $val) {

									if ($val["product_number"]) {

										//check for duplicates
										if ($this->db->RowCount($this->tables["products"] , "WHERE product_number='{$val[product_number]}'")) {
											//okay, i already have this id
											if ($_POST["duplicates"] == 2){
												$this->db->QueryUpdate($this->tables["products"] , $val , " product_number='{$val[product_number]}'");
											}
										} else {
											$val["user_date"] = time();
											$this->db->QueryInsert($this->tables["products"] , $val);
										}
									}
								}							
							}

							header("location: " . $form->vars["form"]["redirect"]);
							exit;

						break;

						case "import.customers":
							$fp = @fopen ($_FILES["file"]["tmp_name"],"r"); 
							while ($import[] = @fgetcsv ($fp, 1000, ","));
							@fclose ($fp); 

							if (is_array($import)) {
								foreach ($import as $key => $record) {
									if ($key != 0) {
										foreach ($import[0] as $k => $val) {
											$_import[$key][$val] = $record[$k];
										}									
									}								
								}							
							}
							
							if (is_array($_import)) {
								foreach ($_import as $key => $val) {

									if ($val["client_name"]) {

										//do the user replacement
										$user = $this->db->QFetchArray("SELECT * FROM {$this->tables[customers]} WHERE client_name='{$val[client_name]}'");
										//check for duplicates
										if ($this->db->RowCount($this->tables["customers"] , "WHERE client_name='{$val[client_name]}'")) {
											//okay, i already have this id
											if ($_POST["duplicates"] == 2){
												$this->db->QueryUpdate($this->tables["customers"] , $val , " client_name='{$val[client_name]}'");
											}
										} else {
											$this->db->QueryInsert($this->tables["customers"] , $val);
										}
									}
								}							
							}

							header("location: " . $form->vars["form"]["redirect"]);
							exit;

						break;

						default:
							$this->vars->SetAll($_POST);
							$this->vars->Save();

							header("location: " . $form->vars["form"]["redirect"]);
							exit;
						break;
					}					
				}				
			}
					
			return $data->Show($_CONF["forms"]["adminpath"] . $file , array("values"=>$this->vars->data));

		break;


	}
}

?>
